<?php

namespace app\admin\controller;

use think\Request;
use app\admin\model\Image;
use app\common\Common;
use app\common\BaseHelper as Helper;
//邀请有礼
class Invitation extends Base
{
    public function _initialize()
    {
        parent::_initialize();
        $this->model = 'invitation';
        $defaultWhere = $this->getDefaultWhere();
        $this->defaultWhere = $defaultWhere;
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $model = model('coupon');
        $coupon = $model->where('coupon_purpose',3)->select();
        $this->assign('coupon',$coupon);

        $model = model($this->model);
        // Get data info
        $info = $model->find(['id'=>1]);

        $info['invitation_rules'] = json_decode($info['invitation_rules'], true);
        return $this->fetch($this->indexView, [
            'info' => $info
        ]);


        return parent::index();
    }

    //添加资源
    public function savePost(Request $request, $redirect='')
    {
        $data = $request->param();
        $model = model($this->model);
        if (empty($data['name'])){
            return $this->error('活动名称未填写');
        }
        if (empty($data['img_url'])){
            return $this->error('活动图片未填写');
        }
        if(isset($data['invitation']) && $data['invitation']){
            foreach ($data['invitation'] as $key => $val) {
                if(!trim($val)){
                    continue;
                }
                $ruleJson[] = [
                    'invitation' => $val,
                    'member' => $data['member'][$key],
                    'status' => 0
                ];
            }
        }
        $data['invitation_rules'] = json_encode($ruleJson);

        $data['id'] = 1;
        $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
        if (!$result){
            return $this->error('修改失败');
        }
        //清空领取积分表
        $integralGet = model('IntegralGet');
        $integralGet->where(['id'=>['neq',0]])->delete();
        $logInfo = $this->admin->name . '修改了一条' . lang($this->model) . '数据。';

        $afterAction = '_after_insert';
        if($result !== false) {
            // 单图
            if(isset($data['img_id']) && !empty($data['img_id'])){
                Image::where('id', $data['img_id'])->update(['related_id' => $data['id'], 'related_table' => 'member_level']);
            }

            // Query执行后的操作
            $model->$afterAction($data);

            // 写入日志
            Common::adminLog($request, $logInfo);

            return $this->success('编辑成功！', 'admin/' . strtolower($this->model) . '/index');
        } else {
            return $this->error($model->getError());
        }
    }
}
